package com.example.criminalintent.model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import org.json.JSONException;

import android.content.Context;
import android.util.Log;

public class CrimeLab {
	
	private static final String TAG = "CrimeLab";
	private static final String JSON_FILE_NAME = "crimes.json";
	
	private static CrimeLab sCrimeLab;
	private Context mAppContext;
	private ArrayList<Crime> mCrimes;
	private CriminalIntentJSONSerializer mSerializer;
	
	public CrimeLab(Context appContext) {
		mAppContext = appContext;
		// Create Serializer to save Crime List to crimes.json
		mSerializer = new CriminalIntentJSONSerializer(mAppContext, JSON_FILE_NAME);
		// Load ArrayList of Crime
		try {
			mCrimes = mSerializer.loadCrimes();
		} catch (IOException e) {
			Log.e(TAG, "Error loading crimes: " + e);
			mCrimes = new ArrayList<Crime>();
		} catch (JSONException e) {
			Log.e(TAG, "Error loading crimes: " + e);
			mCrimes = new ArrayList<Crime>();
		}
	}
	
	public static CrimeLab get(Context c) {
		if (sCrimeLab == null) {
			sCrimeLab = new CrimeLab(c.getApplicationContext());
		}
		return sCrimeLab;
	}
	
	public ArrayList<Crime> getCrimes() {
		return mCrimes;
	}
	
	public Crime getCrime(UUID id) {
		for (Crime item : mCrimes) {
			if (item.getID().equals(id)) {
				return item;
			}
		}
		return null;
	}
	
	public void addCrime(Crime c) {
		mCrimes.add(c);
	}
	
	public boolean saveCrimes() {
		try {
			mSerializer.saveCrimes(mCrimes);
			Log.i(TAG, "Crime list saved to file.");
			return true;
		} catch (IOException e) {
			Log.e(TAG, "Error saving crime list: " + e);
			return false;
		} catch (JSONException e) {
			Log.e(TAG, "Error saving crime list: " + e);
			return false;
		}
	}
	
	public void deleteCrime(Crime c) {
		mCrimes.remove(c);
	}
}
